package com.example.baiguangsystem.config;

import com.example.baiguangsystem.entity.Author;
import com.example.baiguangsystem.entity.Book;
import com.example.baiguangsystem.vo.ResultType;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 书本类和作者类的date属性格式化增强器(没有使用)
 *
 * @Author: 27641
 * @ProjectName: BaiGuangSystem
 * @Date: 2022/02/04/22:42
 * @noinspection SpellCheckingInspection
 */
/*@ControllerAdvice(basePackages = "com.example.baiguangsystem.constroller.BookController")*/
public class BookDateTransformIntercept implements ResponseBodyAdvice<Object> {

    /**
     * 判断那些接口需要进行返回值包装
     *
     * @param returnType
     * @param converterType
     * @return true支持，false不支持
     */
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {

        return true;
    }

    /**
     * 处理response的具体业务方法实现
     *
     * @param body                  返回数据
     * @param returnType            返回类型
     * @param selectedContentType
     * @param selectedConverterType
     * @param request
     * @param response
     * @return
     */
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  ServerHttpRequest request, ServerHttpResponse response) {
        if ((body instanceof Book) && (body != null)) {
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
            Book book = (Book) body;
            Author author = book.getAuthor();
            author.setAuthorDateFormat(dateFormat.format(author.getAuthorDate()));
            return ResultType.success("增强器已经对数据进行了再次封装！", body);
        }
        return ResultType.fail("控制器返回数据为null，增强器没有进行再次封装！");
    }
}
